package user_follow

import (
	"sweetsunnyflower/pkg/app"
	"sweetsunnyflower/pkg/database"
	"sweetsunnyflower/pkg/paginator"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Get(idstr string) (userFollow UserFollow) {
	database.DB.Where("id", idstr).First(&userFollow)
	return
}

func GetBy(field, value string) (userFollow UserFollow) {
	database.DB.Where("? = ?", field, value).First(&userFollow)
	return
}

func All() (userFollows []UserFollow) {
	database.DB.Find(&userFollows)
	return
}

func IsExist(field, value string) bool {
	var count int64
	database.DB.Model(UserFollow{}).Where("? = ?", field, value).Count(&count)
	return count > 0
}

func Paginate(c *gin.Context, perPage int) (userFollows []UserFollow, paging paginator.Paging) {
	paging = paginator.Paginate(
		c,
		database.DB.Model(UserFollow{}),
		&userFollows,
		app.V1URL(database.TableName(&UserFollow{})),
		perPage,
	)
	return
}

func GetUserFollows(userID uint64) (userFollows []UserFollow) {
	database.DB.Preload("User").Where("user_id = ?", userID).Find(&userFollows)
	return
}

func IsFollow(userID uint64, followID uint64) (exist bool, userFollow *UserFollow, err error) {

	err = database.DB.Where("user_id = ?", userID).Where("follow_id = ?", followID).First(&userFollow).Error

	if err != nil {
		if err == gorm.ErrRecordNotFound {
			return false, nil, nil
		} else {
			return false, nil, err
		}
	}

	return true, userFollow, nil
}
